﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using jSLCore.Client.Presentation.AuthorizeService;
using jSLCore.Client.Presentation.BaseControl;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Client.Presentation.BaseControl.Selection;
using jSLCore.Utility.Extensions;

namespace jSLCore.Client.Presentation.Authorization.Managment
{
    public partial class RoleDetail : DialogControl
    {
        private readonly Guid _roleId;

        /// <summary>
        /// for desugner only
        /// </summary>
        public RoleDetail()
        {
            InitializeComponent();
        }

        public RoleDetail(Guid roleId)
        {
            _roleId = roleId;
            InitializeComponent();
        }

        #region Logic
        private void addPermission_Clicked(object sender, RoutedEventArgs e)
        {
            var dlg = new PermissionList {SelectionMode = GridSelectionMode.MultiRow};
            dlg.ShowDialog(delegate(object o, IEnumerable<object> data)
                               {
                                   var warnOn = string.Empty;
                                   foreach (PermissionDescription perm in data)
                                   {
                                       if(CurrentPermissions.Any(cp=>cp.Permission==perm.Permission))
                                       {
                                           warnOn += perm.Name + ", ";
                                       }
                                       else
                                       {
                                           CurrentPermissions.Add(perm);
                                       }
                                   }
                                   if(!string.IsNullOrEmpty(warnOn))
                                   {
                                       warnOn = warnOn.Substring(warnOn.Length - 2);
                                   }


                               }, this);
        }

        private void deletePermission_Clicked(object sender, RowSelectedEventArgs rowSelectedEventArgs)
        {
            CurrentPermissions.Remove((PermissionDescription) rowSelectedEventArgs.RowObject);
        }

        private void addRole_Clicked(object sender, RoutedEventArgs e)
        {
            var dlg = new RolesList() { SelectionMode = GridSelectionMode.MultiRow };
            dlg.ShowDialog(delegate(object o, IEnumerable<object> data)
            {
                var warnOn = string.Empty;
                foreach (Role role in data)
                {
                    if (BaseRoles.Any(cp => cp.id == role.id))
                    {
                        warnOn += role.Name + ", ";
                    }
                    else
                    {
                        BaseRoles.Add(role);
                    }
                }
                if (!string.IsNullOrEmpty(warnOn))
                {
                    warnOn = warnOn.Substring(warnOn.Length - 2);
                }


            }, this);
        }

        private void deleteRole_Clicked(object sender, RowSelectedEventArgs rowSelectedEventArgs)
        {
            BaseRoles.Remove((Role) rowSelectedEventArgs.RowObject);
        } 
        #endregion

        public override void LoadInitialData() 
        {
            DoWork("Загрузка роли",(sender, args) =>
                                       {
                                           args.Result = Communication.Proxy.GetRole(args.Guid);
                                       },(o, eventArgs) =>
                                                             {
                                                                 if(eventArgs.Error==null)
                                                                 {
                                                                     SetDataContext((Role) eventArgs.Result);
                                                                 }
                                                             },_roleId);
        }

        #region CurrentData

        private Role Role
        {
            get { return (Role) DataContext; }
            set { DataContext = value; }
        }

        private ObservableCollection<PermissionDescription> CurrentPermissions
        {
            get { return (ObservableCollection<PermissionDescription>) curPermGrid.ItemsSource; }
            set { curPermGrid.ItemsSource = value; }
        }
        private PermissionDescription[] BasesPermissions
        {
            get { return (PermissionDescription[]) allPermGrid.ItemsSource; }
            set { allPermGrid.ItemsSource = value; }
        }
        private ObservableCollection<Role> BaseRoles
        {
            get { return (ObservableCollection<Role>) roleGrid.ItemsSource; }
            set { roleGrid.ItemsSource = value; }
        }
        

        private void SetDataContext(Role role)
        {
            Role = role;
            Bind();
            BaseRoles = role.BaseRoles.ToObservableCollection();
            CurrentPermissions = role.PermissionCash.ToObservableCollection();

            DoWork("Загрузка всех разрешений",(sender, args) =>
                                                         {
                                                             args.Result =
                                                                 Communication.Proxy.GetInheritedPermissions(args.Guid);
                                                         },(o, eventArgs) =>
                                                                               {
                                                                                   if(eventArgs.Error==null)
                                                                                   {
                                                                                       BasesPermissions =
                                                                                           (PermissionDescription[]) eventArgs.Result;
                                                                                   }
                                                                               },role.id);

        }
        #endregion

        #region Dialog

        public override void OkClicked()
        {
            //Preparing for linked data save

            Role.PermissionCash = CurrentPermissions.ToArray();
            Role.BaseRoles = BaseRoles.ToArray();

            DoWork("Сохранение роли",(sender, args) =>
                                         {
                                             Communication.Proxy.SaveRole((Role) args.Argument);
                                         },(o, eventArgs) =>
                                                               {
                                                                   if(eventArgs.Error==null)
                                                                   {
                                                                       InfoBox.ShowDialog("Роль сохранена");
                                                                       InvokeDataSelected();
                                                                   }
                                                               },Role);
        }

        public override bool IsStandartOkCancelEnabled
        {
            get { return true; }
        }

        public override Control GetControlForInitialFocus()
        {
            return txt;
        } 
        #endregion

        private void gotoRole_Clicked(object sender, RowSelectedEventArgs e)
        {
            var role = (Role)e.RowObject;
            new RoleDetail(role.id).ShowDialog(this);
        }
    }
}
